using Avalonia.Controls;
using Avalonia.Interactivity;
using IntegratedMeasuring.ViewModels.Scheme;
using IntegratedMeasuring.Storage;
using IntegratedMeasuring.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using Avalonia.Collections;
using System.Threading.Tasks;
using System.IO;
using OfficeOpenXml;
using System.Drawing;
using IntegratedMeasuring.ViewModels.Entity;

namespace IntegratedMeasuring.Pages;

public partial class TestHistoryPage : UserControl
{
    private List<ProductInfo> _allTestRecords = new();
    private DataGridCollectionView? _testHistoryView;
    private List<string> _allOrderNames = new();
    private List<string> _allBatchNumbers = new();

    private string BaseUrl = "";
    private const string BaseUrl1 = @"\\192.168.1.1\光順共享\光順共用區\制二部\13.車用機種生產資料存放（共用）";
    private const string BaseUrl2 = @"\\192.168.1.1\光順共享\光順共用區\制二部\17.非車用機種生產資料存放（公用無刪）";
    public TestHistoryPage()
    {
        InitializeComponent();
        Loaded += OnLoaded;
        OrderNameAutoCompleteBox.TextChanged += OrderNameAutoCompleteBox_TextChanged;
    }

    private async void OnLoaded(object sender, RoutedEventArgs e)
    {
        await LoadOrderNamesAsync();
        await LoadBatchNumbersAsync();
        // 初始化空表格，不查全表
        _allTestRecords = new List<ProductInfo>();
        _testHistoryView = new DataGridCollectionView(_allTestRecords);
        TestHistoryDataGrid.ItemsSource = _testHistoryView;
    }

    private async Task LoadOrderNamesAsync()
    {
        var orders = await BaseDataStorage.Instance.LoadProductionOrdersAsync();
        _allOrderNames = orders.Select(o => o.Name).Distinct().ToList();
        OrderNameAutoCompleteBox.ItemsSource = _allOrderNames;
    }

    private async Task LoadBatchNumbersAsync()
    {
        var orders = await BaseDataStorage.Instance.LoadProductionOrdersAsync();
        _allBatchNumbers = orders.Select(o => o.BatchNumber).Distinct().ToList();
        BatchNumberAutoCompleteBox.ItemsSource = _allBatchNumbers;
    }

    private async void OrderNameAutoCompleteBox_TextChanged(object? sender, EventArgs e)
    {
        string orderName = OrderNameAutoCompleteBox.Text?.Trim() ?? "";
        var orders = await BaseDataStorage.Instance.LoadProductionOrdersAsync();
        List<string> batchNumbers;
        if (string.IsNullOrEmpty(orderName))
        {
            batchNumbers = orders.Select(o => o.BatchNumber).Distinct().ToList();
        }
        else
        {
            batchNumbers = orders
                .Where(o => o.Name.Contains(orderName, StringComparison.OrdinalIgnoreCase))
                .Select(o => o.BatchNumber)
                .Distinct()
                .ToList();
        }
        BatchNumberAutoCompleteBox.ItemsSource = batchNumbers;
    }

    private async void SearchButton_Click(object? sender, RoutedEventArgs e)
    {
        try
        {
            var startDate = StartDatePicker.SelectedDate;
            var endDate = EndDatePicker.SelectedDate;
            if (!startDate.HasValue)
            {
                startDate = DateTime.Now.AddDays(-30);
            }
            if (!endDate.HasValue)
            {
                endDate = DateTime.Now;
            }
            if (startDate > endDate)
            {
                NotificationHelper.ShowWarning("日期错误", "开始时间不能晚于结束时间！");
                return;
            }
            // {
            //     NotificationHelper.ShowWarning("搜索提示", "请先选择开始时间和结束时间！");
            //     return;
            // }
            string barcode = ""; //BarcodeTextBox.Text?.Trim() ?? "";
            string orderName = OrderNameAutoCompleteBox.Text?.Trim() ?? "";
            string batchNumber = BatchNumberAutoCompleteBox.Text?.Trim() ?? "";
            string resultFilter = "";
            int? resultInt = null;
            if (ResultComboBox.SelectedItem is ComboBoxItem selectedItem)
            {
                resultFilter = selectedItem.Content?.ToString() ?? "";
                if (resultFilter == "PASS") resultInt = 1;
                else if (resultFilter == "FAIL") resultInt = 0;
            }
            await LoadingHelper.ExecuteWithLoadingAsync(this, async () =>
            {
                List<ProductInfo> filteredData = new();
                // 工单号或周期号有输入，先查ProductionOrder
                if (!string.IsNullOrEmpty(orderName) || !string.IsNullOrEmpty(batchNumber))
                {
                    var orderList = await BaseDataStorage.Instance.QueryProductionOrdersByNameAndBatch(orderName, batchNumber);
                    if (orderList.Count == 0)
                    {
                        NotificationHelper.ShowWarning("无数据", "没有符合条件的工单周期。");
                        _testHistoryView = new DataGridCollectionView(new List<ProductInfo>());
                        TestHistoryDataGrid.ItemsSource = _testHistoryView;
                        return;
                    }
                    var conditionIds = orderList.Select(x => x.Id).ToList();
                    filteredData = await BaseDataStorage.Instance.QueryProductInfoByTimeAndConditionIds(
                        startDate.Value, endDate.Value, conditionIds, barcode, resultInt);
                }
                else
                {
                    filteredData = await BaseDataStorage.Instance.QueryProductInfoByTime(
                        startDate.Value, endDate.Value, barcode, resultInt);
                }
                // 查到数据后批量查工单信息并补充显示字段
                if (filteredData.Count == 0)
                {
                    NotificationHelper.ShowWarning("无数据", "没有符合条件的测试记录。");
                    _testHistoryView = new DataGridCollectionView(new List<ProductInfo>());
                    TestHistoryDataGrid.ItemsSource = _testHistoryView;
                    return;
                }
                var conditionIdList = filteredData.Select(x => x.ConditionId).Distinct().ToList();
                var orderDict = (await BaseDataStorage.Instance.QueryProductionOrdersByIdsAsync(conditionIdList))
                    .ToDictionary(x => x.Id, x => x);
                int i = 0;
                foreach (var record in filteredData)
                {

                    filteredData[i].index = i + 1;
                    if (orderDict.TryGetValue(record.ConditionId, out var order))
                    {
                        record.OrderName = order.Name;
                        record.BatchNumber = order.BatchNumber;
                        record.TestCondition = order.TestConditions;
                    }
                    else
                    {
                        record.OrderName = "";
                        record.BatchNumber = "";
                        record.TestCondition = "";
                    }
                    i++;
                }

                _testHistoryView = new DataGridCollectionView(filteredData);
                TestHistoryDataGrid.ItemsSource = _testHistoryView;
            }, "搜索中...");
        }
        catch (Exception ex)
        {
            NotificationHelper.ShowError("搜索失败", ex.Message);
        }
    }

    private async void ExportButton_Click(object? sender, RoutedEventArgs e)
    {
        var startDate = StartDatePicker.SelectedDate;
        var endDate = EndDatePicker.SelectedDate;
        var category = CategoryComboBox.SelectedItem as ComboBoxItem;
        if (category == null || category.Content == null)
        {
            NotificationHelper.ShowWarning("导出提示", "请选择导出类别！");
            return;
        }
        else if (category.Content.ToString() == "车用")
        {
            BaseUrl = BaseUrl1;
        }
        else if (category.Content.ToString() == "非车用")
        {
            BaseUrl = BaseUrl2;
        }
        if (!startDate.HasValue)
        {
            startDate = DateTime.Now.AddDays(-30);
        }
        if (!endDate.HasValue)
        {
            endDate = DateTime.Now;
        }
        if (startDate > endDate)
        {
            NotificationHelper.ShowWarning("日期错误", "开始时间不能晚于结束时间！");
            return;
        }
        try
        {
            await LoadingHelper.ExecuteWithLoadingAsync(this, async () =>
            {
                // 获取当前显示的数据
                var currentData = _testHistoryView?.Cast<ProductInfo>().ToList() ?? new List<ProductInfo>();
                if (currentData.Count == 0)
                {
                    NotificationHelper.ShowWarning("导出提示", "没有数据可导出");
                    return;
                }

                // 检查是否只有一个工单周期
                var orderBatchGroups = currentData
                    .GroupBy(x => new { x.OrderName, x.BatchNumber })
                    .ToList();

                if (orderBatchGroups.Count > 1)
                {
                    NotificationHelper.ShowWarning("导出提示", "单次只能导出一个工单与周期，请缩小搜索范围");
                    return;
                }

                var orderInfo = orderBatchGroups.First();
                var orderName = orderInfo.Key.OrderName;
                var batchNumber = orderInfo.Key.BatchNumber;
                var orderList = await BaseDataStorage.Instance.AccurateQueryProductionOrdersByNameAndBatch(orderName, batchNumber);
                // // 创建保存文件对话框
                // var saveFileDialog = new SaveFileDialog
                // {
                //     Title = "导出测试历史数据",
                //     Filters = new List<FileDialogFilter>
                //     {
                //         new FileDialogFilter { Name = "Excel文件", Extensions = new List<string> { "xlsx" } }
                //     },
                //     DefaultExtension = "xlsx",
                //     InitialFileName = $"测试历史_{orderName}_{batchNumber}_{DateTime.Now:yyyyMMddHHmmss}.xlsx"
                // };

                var window = this.VisualRoot as Window;
                //var result = await saveFileDialog.ShowAsync(window);
                var ParamName = orderList.First().TestConditions.ToString();
                var result = Path.Combine(BaseUrl, ParamName
                    );

                //$"测试历史_{orderName}_{batchNumber}_{DateTime.Now:yyyyMMddHHmmss}.xlsx
                if (!Directory.Exists(result))
                {
                    Directory.CreateDirectory(result);
                }

                //result = Path.Combine(result, $"{orderName}_{batchNumber}_{DateTime.Now:yyyyMMddHHmmss}.xlsx");

                if (!string.IsNullOrEmpty(result))
                {

                    await ExportToExcel([.. currentData.Where(X => X.Result == 1)], Path.Combine(result, $"{orderName}_{ParamName}_{batchNumber}_OK.xlsx"), orderName, batchNumber);
                    await ExportToExcel([.. currentData.Where(X => X.Result == 0)], Path.Combine(result, $"{orderName}_{ParamName}_{batchNumber}_NG.xlsx"), orderName, batchNumber);
                    await ExportToExcel(currentData, Path.Combine(result, $"{orderName}_{ParamName}_{batchNumber}_ALL.xlsx"), orderName, batchNumber);


                    // 更新对应工单的导出时间和导出位置
                    //  var orderList = await BaseDataStorage.Instance.AccurateQueryProductionOrdersByNameAndBatch(orderName, batchNumber);
                    if (orderList.Count > 0)
                    {
                        var order = orderList[0];
                        order.ExportTime = DateTime.Now;
                        order.ExportPath = result;
                        await BaseDataStorage.Instance.UpdateProductionOrderAsync(order);
                    }

                    NotificationHelper.ShowSuccess("导出成功", $"已导出 {currentData.Count} 条记录到 {result}");
                }
            }, "导出中...");
        }
        catch (Exception ex)
        {
            NotificationHelper.ShowError("导出失败", ex.Message);
        }
    }

    private async Task ExportToExcel(List<ProductInfo> data, string filePath, string orderName, string batchNumber)
    {
        ExcelPackage.License.SetNonCommercialPersonal("FGKJ");
        using (var package = new ExcelPackage())
        {
            var worksheet = package.Workbook.Worksheets.Add("测试历史");

            // 设置第一行行高、第一列列宽最小
            worksheet.Row(1).Height = 1;
            worksheet.Column(1).Width = 0;

            // 工单信息表格Label列分别在E、G、I，值在F、H、J
            var testCondition = data.FirstOrDefault()?.TestCondition ?? "";
            var passCount = data.Count(x => x.Result == 1);
            var failCount = data.Count(x => x.Result == 0);
            var deviceNumber = GV.DeviceNumber;
            var testUser = "";   // 暂时先不管，后续看要不要加账号模块

            int pNumber = 0;
            var orderList = await BaseDataStorage.Instance.AccurateQueryProductionOrdersByNameAndBatch(orderName, batchNumber);
            if (orderList.Count > 0)
            {
                pNumber = orderList[0].PlanNumber;
            }

            worksheet.Cells["E2"].Value = "机种名称";
            worksheet.Cells["F2"].Value = testCondition;
            worksheet.Cells["G2"].Value = "测试数量";
            worksheet.Cells["H2"].Value = data.Count;
            worksheet.Cells["I2"].Value = "工单数量";
            worksheet.Cells["J2"].Value = pNumber;

            worksheet.Cells["E3"].Value = "工单编号";
            worksheet.Cells["F3"].Value = orderName;
            worksheet.Cells["G3"].Value = "PASS数量";
            worksheet.Cells["H3"].Value = passCount;
            worksheet.Cells["I3"].Value = "设备编号";
            worksheet.Cells["J3"].Value = deviceNumber;

            worksheet.Cells["E4"].Value = "生产周期";
            worksheet.Cells["F4"].Value = batchNumber;
            worksheet.Cells["G4"].Value = "NG数量";
            worksheet.Cells["H4"].Value = failCount;
            worksheet.Cells["I4"].Value = "测试人员";
            worksheet.Cells["J4"].Value = testUser;

            // 设置工单信息表格样式
            var labelCells = new[] { "E2", "G2", "I2", "E3", "G3", "I3", "E4", "G4", "I4" };
            foreach (var cell in labelCells)
            {
                var c = worksheet.Cells[cell];
                c.Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;
                c.Style.Fill.BackgroundColor.SetColor(Color.FromArgb(0, 176, 240)); // 新浅蓝色
                c.Style.Font.Size = 14;
                c.Style.Font.Bold = true;
                c.Style.Font.Color.SetColor(Color.White);
                c.Style.Border.BorderAround(OfficeOpenXml.Style.ExcelBorderStyle.Thin, Color.Black);
                c.Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;
                c.Style.VerticalAlignment = OfficeOpenXml.Style.ExcelVerticalAlignment.Center;
            }

            // 工单信息表格整体外框加黑色边框
            var orderInfoRange = worksheet.Cells["E2:J4"];
            orderInfoRange.Style.Border.Top.Style = OfficeOpenXml.Style.ExcelBorderStyle.Thin;
            orderInfoRange.Style.Border.Bottom.Style = OfficeOpenXml.Style.ExcelBorderStyle.Thin;
            orderInfoRange.Style.Border.Left.Style = OfficeOpenXml.Style.ExcelBorderStyle.Thin;
            orderInfoRange.Style.Border.Right.Style = OfficeOpenXml.Style.ExcelBorderStyle.Thin;
            orderInfoRange.Style.Border.Top.Color.SetColor(Color.Black);
            orderInfoRange.Style.Border.Bottom.Color.SetColor(Color.Black);
            orderInfoRange.Style.Border.Left.Color.SetColor(Color.Black);
            orderInfoRange.Style.Border.Right.Color.SetColor(Color.Black);

            // 根据机种名称查询测试条件
            TestConditions? testConditions = null;
            if (!string.IsNullOrEmpty(testCondition))
            {
                testConditions = await BaseDataStorage.Instance.QueryTestConditionsByNameAsync(testCondition);
            }

            // 测试项目竖向表格 (从B6开始)
            if (testConditions?.BeautifyData != null && testConditions.BeautifyData.Count > 0)
            {
                // 只移除Pri=0且Sec=0的TURN项目
                var testItems = new List<TransItemData>(testConditions.BeautifyData);
                int firstTurnItemIdx = testItems.FindIndex(item => item.MinorTerm == "TURN" && item.Pri == 0 && item.Sec == 0);
                if (firstTurnItemIdx >= 0)
                {
                    testItems.RemoveAt(firstTurnItemIdx);
                }

                if (testItems.Count > 0)
                {
                    // 设置测试项目行标题 (B6:B14)，合并B到F列单元格
                    var testLabels = new[]
                    {
                        "测试项目", "测试频率", "测试电压", "测试脚位", "并联脚位",
                        "短路脚位", "标称值", "下限", "上限"
                    };

                    for (int i = 0; i < testLabels.Length; i++)
                    {
                        var cell = worksheet.Cells[6 + i, 2];
                        cell.Value = testLabels[i];
                        // 合并B到F列单元格
                        worksheet.Cells[6 + i, 2, 6 + i, 6].Merge = true;
                        var mergedCell = worksheet.Cells[6 + i, 2, 6 + i, 6];
                        mergedCell.Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;
                        mergedCell.Style.Fill.BackgroundColor.SetColor(Color.FromArgb(0, 176, 240));
                        mergedCell.Style.Font.Size = 14;
                        mergedCell.Style.Font.Bold = true;
                        mergedCell.Style.Font.Color.SetColor(Color.White);
                        mergedCell.Style.Border.BorderAround(OfficeOpenXml.Style.ExcelBorderStyle.Thin, Color.Black);
                        mergedCell.Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;
                        mergedCell.Style.VerticalAlignment = OfficeOpenXml.Style.ExcelVerticalAlignment.Center;
                    }

                    // 填充测试项目数据 (从G列开始，每个项目占一列)
                    for (int i = 0; i < testItems.Count; i++)
                    {
                        var item = testItems[i];
                        int col = 7 + i; // G列是第7列

                        worksheet.Cells[6, col].Value = item.MinorTerm ?? ""; // 测试项目
                        worksheet.Cells[7, col].Value = item.Freq ?? ""; // 测试频率
                        worksheet.Cells[8, col].Value = item.Vol ?? ""; // 测试电压
                        worksheet.Cells[9, col].Value = item.Pins ?? ""; // 测试脚位
                        worksheet.Cells[10, col].Value = item.ParallelPin ?? ""; // 并联脚位
                        worksheet.Cells[11, col].Value = item.ShortCircuitPin ?? ""; // 短路脚位
                        worksheet.Cells[12, col].Value = item.Nominal ?? ""; // 标称值
                        worksheet.Cells[13, col].Value = item.LowerLimit ?? ""; // 下限
                        worksheet.Cells[14, col].Value = item.UpperLimit ?? ""; // 上限
                    }

                    // 设置测试项目表格边框
                    var lastCol = GetColumnLetter(6 + testItems.Count);
                    var testItemsRange = worksheet.Cells[$"B6:{lastCol}14"];
                    testItemsRange.Style.Border.Top.Style = OfficeOpenXml.Style.ExcelBorderStyle.Thin;
                    testItemsRange.Style.Border.Bottom.Style = OfficeOpenXml.Style.ExcelBorderStyle.Thin;
                    testItemsRange.Style.Border.Left.Style = OfficeOpenXml.Style.ExcelBorderStyle.Thin;
                    testItemsRange.Style.Border.Right.Style = OfficeOpenXml.Style.ExcelBorderStyle.Thin;
                    testItemsRange.Style.Border.Top.Color.SetColor(Color.Black);
                    testItemsRange.Style.Border.Bottom.Color.SetColor(Color.Black);
                    testItemsRange.Style.Border.Left.Color.SetColor(Color.Black);
                    testItemsRange.Style.Border.Right.Color.SetColor(Color.Black);

                    // 设置测试数据表头 (紧挨着测试项目表格，从第15行开始)
                    int dataHeaderRow = 15;
                    worksheet.Cells[$"B{dataHeaderRow}"].Value = "序号";
                    worksheet.Cells[$"C{dataHeaderRow}"].Value = "条码";
                    worksheet.Cells[$"D{dataHeaderRow}"].Value = "测试开始时间";
                    worksheet.Cells[$"E{dataHeaderRow}"].Value = "测试结束时间";
                    worksheet.Cells[$"F{dataHeaderRow}"].Value = "总判定";

                    // 添加测试项目明细列标题
                    for (int i = 0; i < testItems.Count; i++)
                    {
                        int col = 7 + i; // G列是第7列
                        worksheet.Cells[dataHeaderRow, col].Value = testItems[i].MinorTerm ?? "";
                    }

                    var dataHeaderRange = worksheet.Cells[$"B{dataHeaderRow}:{lastCol}{dataHeaderRow}"];
                    dataHeaderRange.Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;
                    dataHeaderRange.Style.Fill.BackgroundColor.SetColor(Color.FromArgb(0, 176, 240));
                    dataHeaderRange.Style.Font.Size = 14;
                    dataHeaderRange.Style.Font.Bold = true;
                    dataHeaderRange.Style.Font.Color.SetColor(Color.White);
                    dataHeaderRange.Style.Border.BorderAround(OfficeOpenXml.Style.ExcelBorderStyle.Thin, Color.Black);
                    dataHeaderRange.Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;
                    dataHeaderRange.Style.VerticalAlignment = OfficeOpenXml.Style.ExcelVerticalAlignment.Center;

                    // 批量查询所有测试记录，避免逐行查询数据库
                    var allProductIds = data.Select(x => x.Id).ToList();
                    var allTestRecords = await BaseDataStorage.Instance.QueryAsync<TestRecord>(x => allProductIds.Contains(x.ProductId));

                    // 按ProductId分组，便于快速查找
                    var testRecordsByProductId = allTestRecords.GroupBy(x => x.ProductId).ToDictionary(g => g.Key, g => g.ToList());

                    // 填充测试数据
                    int dataRow = dataHeaderRow + 1;
                    for (int i = 0; i < data.Count; i++)
                    {
                        var record = data[i];
                        worksheet.Cells[dataRow, 2].Value = i + 1; // 序号
                        worksheet.Cells[dataRow, 3].Value = record.BarCode; // 条码
                        worksheet.Cells[dataRow, 4].Value = record.StartTime.ToString("yyyy-MM-dd HH:mm:ss"); // 测试开始时间
                        worksheet.Cells[dataRow, 5].Value = record.EndTime.ToString("yyyy-MM-dd HH:mm:ss"); // 测试结束时间

                        // 总判定列，设置背景色
                        var resultCell = worksheet.Cells[dataRow, 6];
                        resultCell.Value = record.Result == 1 ? "PASS" : "FAIL";
                        if (record.Result == 1)
                        {
                            resultCell.Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;
                            resultCell.Style.Fill.BackgroundColor.SetColor(Color.FromArgb(212, 237, 218)); // 浅绿色
                        }
                        else
                        {
                            resultCell.Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;
                            resultCell.Style.Fill.BackgroundColor.SetColor(Color.FromArgb(248, 215, 218)); // 浅红色
                        }

                        // 查询并填充测试明细数据
                        if (testRecordsByProductId.TryGetValue(record.Id, out var testRecords))
                        {
                            // 根据测试项目顺序填充明细数据
                            for (int j = 0; j < testItems.Count; j++)
                            {
                                var testItem = testItems[j];
                                // 查找对应的测试记录
                                var matchingRecord = testRecords.FirstOrDefault(tr =>
                                    tr.MinorTerm == testItem.MinorTerm &&
                                    tr.Pri == testItem.Pri &&
                                    tr.Sec == testItem.Sec);

                                if (matchingRecord != null)
                                {
                                    int col = 7 + j; // G列是第7列
                                    string displayValue = $"{matchingRecord.DisplayDetectionValue}{matchingRecord.DisplayUnit}";
                                    worksheet.Cells[dataRow, col].Value = displayValue;
                                }
                            }
                        }

                        dataRow++;
                    }
                }
                else
                {
                    // 没有测试项目数据，直接显示测试数据表头
                    worksheet.Cells["B6"].Value = "序号";
                    worksheet.Cells["C6"].Value = "条码";
                    worksheet.Cells["D6"].Value = "测试开始时间";
                    worksheet.Cells["E6"].Value = "测试结束时间";
                    worksheet.Cells["F6"].Value = "总判定";
                    var headerRange = worksheet.Cells["B6:F6"];
                    headerRange.Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;
                    headerRange.Style.Fill.BackgroundColor.SetColor(Color.FromArgb(0, 176, 240));
                    headerRange.Style.Font.Size = 14;
                    headerRange.Style.Font.Bold = true;
                    headerRange.Style.Font.Color.SetColor(Color.White);
                    headerRange.Style.Border.BorderAround(OfficeOpenXml.Style.ExcelBorderStyle.Thin, Color.Black);
                    headerRange.Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;
                    headerRange.Style.VerticalAlignment = OfficeOpenXml.Style.ExcelVerticalAlignment.Center;

                    // 填充测试数据
                    int row = 7;
                    for (int i = 0; i < data.Count; i++)
                    {
                        var record = data[i];
                        worksheet.Cells[row, 2].Value = i + 1; // 序号
                        worksheet.Cells[row, 3].Value = record.BarCode; // 条码
                        worksheet.Cells[row, 4].Value = record.StartTime.ToString("yyyy-MM-dd HH:mm:ss"); // 测试开始时间
                        worksheet.Cells[row, 5].Value = record.EndTime.ToString("yyyy-MM-dd HH:mm:ss"); // 测试结束时间
                        worksheet.Cells[row, 6].Value = record.Result == 1 ? "PASS" : "FAIL"; // 总判定
                        row++;
                    }
                }
            }
            else
            {
                // 没有测试条件数据，直接显示测试数据表头
                worksheet.Cells["B6"].Value = "序号";
                worksheet.Cells["C6"].Value = "条码";
                worksheet.Cells["D6"].Value = "测试开始时间";
                worksheet.Cells["E6"].Value = "测试结束时间";
                worksheet.Cells["F6"].Value = "总判定";
                var headerRange = worksheet.Cells["B6:F6"];
                headerRange.Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;
                headerRange.Style.Fill.BackgroundColor.SetColor(Color.FromArgb(0, 176, 240));
                headerRange.Style.Font.Size = 14;
                headerRange.Style.Font.Bold = true;
                headerRange.Style.Font.Color.SetColor(Color.White);
                headerRange.Style.Border.BorderAround(OfficeOpenXml.Style.ExcelBorderStyle.Thin, Color.Black);
                headerRange.Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;
                headerRange.Style.VerticalAlignment = OfficeOpenXml.Style.ExcelVerticalAlignment.Center;

                // 填充测试数据
                int row = 7;
                for (int i = 0; i < data.Count; i++)
                {
                    var record = data[i];
                    worksheet.Cells[row, 2].Value = i + 1; // 序号
                    worksheet.Cells[row, 3].Value = record.BarCode; // 条码
                    worksheet.Cells[row, 4].Value = record.StartTime.ToString("yyyy-MM-dd HH:mm:ss"); // 测试开始时间
                    worksheet.Cells[row, 5].Value = record.EndTime.ToString("yyyy-MM-dd HH:mm:ss"); // 测试结束时间
                    worksheet.Cells[row, 6].Value = record.Result == 1 ? "PASS" : "FAIL"; // 总判定
                    row++;
                }
            }

            // 自动调整列宽
            worksheet.Cells.AutoFitColumns();
            if (File.Exists(filePath))
                File.Delete(filePath); // 如果文件已存在，先删除
            // 保存文件
            await package.SaveAsAsync(new FileInfo(filePath));
        }
    }

    /// <summary>
    /// 将列索引转换为Excel列字母
    /// </summary>
    /// <param name="columnIndex">列索引（从1开始）</param>
    /// <returns>Excel列字母</returns>
    private string GetColumnLetter(int columnIndex)
    {
        string result = "";
        while (columnIndex > 0)
        {
            columnIndex--;
            result = (char)('A' + columnIndex % 26) + result;
            columnIndex /= 26;
        }
        return result;
    }

    private async void TestHistoryDataGrid_DoubleTapped(object? sender, Avalonia.Input.TappedEventArgs e)
    {
        try
        {
            // 获取选中的行数据
            if (TestHistoryDataGrid.SelectedItem is ProductInfo selectedProduct)
            {
                // 创建并显示详情弹窗
                var detailDialog = new TestRecordDetailDialog(selectedProduct);
                var window = this.VisualRoot as Window;
                await detailDialog.ShowDialog(window);
            }
        }
        catch (Exception ex)
        {
            NotificationHelper.ShowError("显示详情失败", ex.Message);
        }
    }
}